package com.cloud.order.service.controller;

import cn.hutool.core.util.IdUtil;
import com.cloud.order.service.feign.FeignService;
import com.fuzhixuan.cloud.entities.CommonResult;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class HystrixController {
    @Autowired
    private FeignService feignService;

    @GetMapping(value = "/payment/hystrix/ok")
    public CommonResult<String> getPaymentOk() {
        System.out.println("/payment/hystrix/ok");
        return CommonResult.ok(200, "/payment/hystrix/ok");
    }

    @GetMapping(value = "/payment/hystrix/timeout")
    @HystrixCommand
    public CommonResult<String> getPaymentTimeout() {
        try {
            TimeUnit.SECONDS.sleep(5);
            System.out.println("/payment/hystrix/timeout");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return CommonResult.ok(200, "/payment/hystrix/timeout");
    }

    @GetMapping(value = "/getServerPort")
    public String getPort() {
        return feignService.getPort();
    }

    @GetMapping(value = "/payment/timeout")
    public String timeOut() {
        return feignService.timeOut();
    }

    /**
     * 服务熔断
     * 10s内，调用失败次数超过10*60% = 6次，调用成功的请求，也会失败，后面会自动恢复
     *
     * @param id
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/payment/rongduan/{id}")
    @HystrixCommand(fallbackMethod = "paymentRongDuan", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),
    })
    public Object rongduan(@PathVariable("id") Integer id) throws Exception {
        if (id < 0) {
            throw new Exception("id<0了");
        }
        return "返回随机码：" + IdUtil.simpleUUID();
    }

    public Object paymentRongDuan(@PathVariable("id") Integer id) {
        return "调用失败：id=" + id;
    }
}